package www.xfOnline.ui;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JScrollPane;
import www.xfOnline.dao.JDBCDAO;
import javax.swing.JTextField;
import javax.swing.JLabel;
import www.xfOnline.util.VAR;

public class MsgListFrame extends JFrame {

	private JScrollPane scrollPane;
	private JPanel contentPane;
	private DefaultTableModel dtable;
	private JTable table;
	private JLabel message;
	private JLabel labelError;
	private JLabel labelNow;
	private JLabel labelAll;
	private JTextField tfPage;
	private JTextField tfSearch;
	private JTextField tfAccount;
	private JTextField tfName;
	private JTextField tfSex;
	private JTextField tfEmail;
	private JTextField tfSchool;
	private JDBCDAO jdao;
	private JPanel panel_3;
	private JButton addData;
	private JButton editData;
	private JButton deleteData;
	private ArrayList<Integer> arraylist;
	private int showLine,count,pageNow;
	private String sqlMain;
	private String sqlLike;
	private String sqlGetNum;
	private Object[][] obj;
	private Object[] column = {"账号","姓名","性别","邮箱","学校"};
	/**
	 * Create the frame.
	 **/
	public MsgListFrame() {
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InstantiationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedLookAndFeelException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		labelNow = new JLabel();
		labelAll= new JLabel();
		table = new JTable();
		table.setEnabled(false);
		jdao = new JDBCDAO();
		obj = null;
		sqlMain = "select account,name,sex,email,school from user where 1=1 limit ?,?";
		sqlLike = "select account,name,sex,email,school from user where account like ? or name like ?";
		sqlGetNum = "select count(account) count from user where 1=1";
		arraylist = new ArrayList<Integer>();
		showLine = 0;
		count=0;
		pageNow=1;
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		setBounds(300, 100, 750, 550);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		GridBagLayout gbl_contentPane = new GridBagLayout();
		gbl_contentPane.columnWidths = new int[]{0, 0};
		gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0};
		gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		contentPane.setLayout(gbl_contentPane);
		
		JPanel panel = new JPanel();
		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(0, 0, 5, 0);
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 0;
		contentPane.add(panel, gbc_panel);
		
		addData = new JButton("添加");
		panel.add(addData);
		addData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(addData.getText().equals("添加")){
					panel_3.setVisible(true);	
					addData.setText("取消");
				}else if(addData.getText().equals("取消")){
					panel_3.setVisible(false);
					addData.setText("添加");
				}else{
					showTable();
					panel_3.setVisible(false);
					addData.setText("添加");
				}
			}
		});
		
		table.addKeyListener(new KeyListener() {
			
			public void keyTyped(KeyEvent e) {
				
			}
			
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				if(!arraylist.contains(table.getSelectedRow())){
					arraylist.add(table.getSelectedRow());
				}
			}
			
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				labelEmpty();
			}
		});
		table.addMouseListener(new MouseListener() {
			
			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub
				int row = table.getSelectedColumn();//那一行
				int column = table.getSelectedColumn(); //那一列
				if(table.isEnabled()){
					table.setValueAt(table.getValueAt(row, column), row, column);
				}
			}
			
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub
				if(!arraylist.contains(table.getSelectedRow())){
					arraylist.add(table.getSelectedRow());
				}
				if(deleteData.getText().equals("选择")){
					deleteData.setText("确定");
				}
			}
		});
		editData = new JButton("编辑");
		panel.add(editData);
		editData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(editData.getText().equals("编辑")){
					arraylist.clear();
					table.setEnabled(true);
					editData.setText("保存");
				}else{
					int len = arraylist.size();
					System.out.println(""+len);
					int k=0;
					String message="";
					String sql = "update user set name=? ,sex=? ,email=? ,school=? where account=?";
					for(int i=0;i<len;i++){
						int row = arraylist.get(i);
						table.repaint();
						//dtable.getValueAt(row, 2);
						Object account =  table.getValueAt(row, 0);
						Object name = table.getValueAt(row, 1);
						Object sex = dtable.getValueAt(row, 2);
						Object email = table.getValueAt(row, 3);
						System.out.println(""+row+account+len+name+sex+email);
						if(!email.toString().matches(VAR.matchEmail)){
							message=message+account+",";
							continue;
						}
						Object school = table.getValueAt(row, 4);
						try {
							k=jdao.update(sql, new Object[]{name,sex,email,school,account});
							System.err.println(k+"k-----");
						} catch (Exception e2) {
							e2.printStackTrace();
						}
						if(k!=1){
							message=message+account+",";
						}
					}
					if(message.equals("")){
						labelError.setText("修改成功");
						
					}else{
						labelError.setText(message+"信息格式有错");
					}
					table.setEnabled(false);
					editData.setText("编辑");
				}
			}
		});
		
		deleteData = new JButton("删除");
		panel.add(deleteData);
		deleteData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(deleteData.getText().equals("删除")){
					table.setEnabled(true);
					deleteData.setText("选择");
				}else {
					int row = table.getSelectedRow(),k=0;
					String sql = "delete from user where account = ?";
					Object account =  table.getValueAt(row, 0);
					k=jdao.update(sql, new Object[]{account});
					if(k==1){
						showTable();
						table.setEnabled(false);
						deleteData.setText("删除");
					}else{
						labelError.setText("未知错误");
						table.setEnabled(false);
						deleteData.setText("删除");
					}
				}
			}
		});
		
		tfSearch = new JTextField();
		panel.add(tfSearch);
		tfSearch.setColumns(10);
		tfSearch.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				labelEmpty();
			}
		});
	
		JButton searchData = new JButton("查找");
		panel.add(searchData);
		
		labelError = new JLabel("");
		panel.add(labelError);
		searchData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				String search = "%"+tfSearch.getText()+"%";
				shouLikeTable(search);
			}
		});
		
		panel_3 = new JPanel();
		GridBagConstraints gbc_panel_3 = new GridBagConstraints();
		gbc_panel_3.insets = new Insets(0, 0, 5, 0);
		gbc_panel_3.fill = GridBagConstraints.BOTH;
		gbc_panel_3.gridx = 0;
		gbc_panel_3.gridy = 1;
		contentPane.add(panel_3, gbc_panel_3);
		
		panel_3.setVisible(false);	
		JLabel label = new JLabel("账号");
		panel_3.add(label);
		
		tfAccount = new JTextField();
		panel_3.add(tfAccount);
		tfAccount.setColumns(10);
		
		JLabel label_1 = new JLabel("姓名");
		panel_3.add(label_1);
		
		tfName = new JTextField();
		panel_3.add(tfName);
		tfName.setColumns(10);
		
		JLabel lblNewLabel_2 = new JLabel("性别");
		panel_3.add(lblNewLabel_2);
		
		tfSex = new JTextField();
		panel_3.add(tfSex);
		tfSex.setColumns(10);
		
		JLabel label_2 = new JLabel("邮箱");
		panel_3.add(label_2);
		
		tfEmail = new JTextField();
		panel_3.add(tfEmail);
		tfEmail.setColumns(10);
		
		JLabel label_3 = new JLabel("学校");
		panel_3.add(label_3);
		
		tfSchool = new JTextField();
		panel_3.add(tfSchool);
		tfSchool.setColumns(10);
		
		JButton addConfirm = new JButton("确认");
		addConfirm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				String sql = "insert into user (account,name,sex,email,school,password) values (?,?,?,?,?,?)";
				int i=0;
				long ac=0;
				try{
					 ac = Integer.parseInt(tfAccount.getText());
				}catch (Exception e1){
					message.setText("账号格式错误");
					return;
				}
				if(!tfEmail.getText().matches(VAR.matchEmail)){
					message.setText("邮箱格式错误");
					return;
				}
				i = jdao.update(sql, new Object[]{tfAccount.getText(),tfName.getText(),tfSex.getText(),tfEmail.getText(),tfSchool.getText(),"100000"});
				if(i==1){
					message.setText("用户添加成功");
					addData.setText("收回");
					return;
				}else{
					message.setText("未知错误");
					return;
				}
			}
		});
		panel_3.add(addConfirm);
		
		message = new JLabel("");
		panel_3.add(message);
		
		JPanel panel_1 = new JPanel();
		GridBagConstraints gbc_panel_1 = new GridBagConstraints();
		gbc_panel_1.insets = new Insets(0, 0, 5, 0);
		gbc_panel_1.fill = GridBagConstraints.BOTH;
		gbc_panel_1.gridx = 0;
		gbc_panel_1.gridy = 2;
		contentPane.add(panel_1, gbc_panel_1);
		
		scrollPane = new JScrollPane();
		panel_1.add(scrollPane);
		
		JPanel panel_2 = new JPanel();
		GridBagConstraints gbc_panel_2 = new GridBagConstraints();
		gbc_panel_2.anchor = GridBagConstraints.EAST;
		gbc_panel_2.fill = GridBagConstraints.VERTICAL;
		gbc_panel_2.gridx = 0;
		gbc_panel_2.gridy = 3;
		contentPane.add(panel_2, gbc_panel_2);
		
		JButton previousPage = new JButton("上一页");
		previousPage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				if(showLine<15){
					return;
				}
				pageNow--;
				showPageNum(pageNow,(count/15+1));
				showLine-=15;
				showTable();
			}
		});
		panel_2.add(previousPage);
		
		JButton nextPage = new JButton("下一页");
		nextPage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				if(showLine>count-15){
					return;
				}
				pageNow++;
				showPageNum(pageNow,(count/15+1));
				showLine+=15;
				showTable();
			}
		});
		panel_2.add(nextPage);
		
		tfPage = new JTextField();
		panel_2.add(tfPage);
		tfPage.setColumns(10);
		tfPage.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				labelEmpty();
			}
		});

		JButton jumpPage = new JButton("跳转");
		jumpPage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				labelEmpty();
				int jumpNum=0;
				String str = tfPage.getText();
				try {
					jumpNum = Integer.valueOf(str);
				} catch (Exception e2) {
					labelError.setText("请输入数字");
					return;
				}
				if(jumpNum>(count/15+1)){
					labelError.setText("不能超过总页数"+(count/15+1));
					return;
				}
				if(jumpNum<1){
					labelError.setText("不能小于1");
					return;
				}
				pageNow=jumpNum;
				showLine = 15*(jumpNum-1);
				showPageNum(pageNow,(count/15+1));
				showTable();
			}
		});
		panel_2.add(jumpPage); 
		panel_2.add(labelNow);
		panel_2.add(labelAll);
		
		showPageNum(pageNow,(count/15+1));
		showTable();
	}

	public void shouLikeTable(String str){
		table.removeAll();
		try {
			obj = jdao.ArrayListToArray(jdao.findAll(sqlLike, new Object[]{str,str}, 5));
			showTableInit();
		} catch (Exception e) {
			labelError.setText("没有该用户");
		}
	}
	public void showTable(){
		table.removeAll();
		obj = jdao.ArrayListToArray(jdao.findAll(sqlMain, new Object[]{showLine,15}, 5));//之前sql第二个参数是showLine+15，错误。第二个参数是显示的行数。
		showTableInit();
		showPageNum(pageNow,(count/15+1));
	}
	
	public void showTableInit(){
		HashMap haspMap = new HashMap();
		haspMap = jdao.findOne(sqlGetNum, new Object[]{});
		count = Integer.valueOf(String.valueOf(haspMap.get("count")));
		dtable = new DefaultTableModel(obj,column){      //因为账号的唯一性，规定账号不能修改。
			public boolean isCellEditable(int row,int column){
				if(column==0){
					return false;
				}else{
					return true;	
				}		
			}
		};
		dtable.setRowCount(15);
		table.setRowHeight(22);
		table.setPreferredScrollableViewportSize(new Dimension(600,330));
		table.setModel(dtable);
		scrollPane.setViewportView(table);
	}
	public void showPageNum(int now,int all){
		labelNow.setText("第"+now+"页");
		labelAll.setText("一共"+all+"页");
	}
	public void labelEmpty(){
		message.setText("");
		labelError.setText("");
	}
}
